/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.cloud;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import io.renren.common.exception.RRException;
import io.renren.utils.DateTimeUtil;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * 腾讯云存储
 *
 * @author Mark sunlightcs@gmail.com
 */
public class QcloudCloudStorageService extends CloudStorageService {
    private COSClient client;

    public QcloudCloudStorageService(CloudStorageConfig config){
        this.config = config;

        //初始化
        init();
    }

    private void init(){
        // 1 初始化用户身份信息（secretId, secretKey）。
// SECRETID和SECRETKEY请登录访问管理控制台 https://console.cloud.tencent.com/cam/capi 进行查看和管理
        String secretId = config.getQcloudSecretId();
        String secretKey = config.getQcloudSecretKey();
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2 设置 bucket 的地域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
// clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        String cosRegin=config.getQcloudRegion();
        Region region = new Region(cosRegin);
        ClientConfig clientConfig = new ClientConfig(region);
// 这里建议设置使用 https 协议
// 从 5.6.54 版本开始，默认使用了 https
        clientConfig.setHttpProtocol(HttpProtocol.https);
// 3 生成 cos 客户端。
        client = new COSClient(cred, clientConfig);

    }

    @Override
    public String upload(byte[] data, String path) {

        return "";
    }

    @Override
    public String upload(InputStream inputStream, String path) {
    	try {
            byte[] data = IOUtils.toByteArray(inputStream);
            return this.upload(data, path);
        } catch (IOException e) {
            throw new RRException("上传文件失败", e);
        }
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix,File file) {
        return uploadFile(file);
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        String url;
        try {
// 指定文件将要存放的存储桶
            String bucketName = config.getQcloudBucketName();
// 指定文件上传到 COS 上的路径，即对象键。例如对象键为folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
            ObjectMetadata metadata=new ObjectMetadata();
            Long  timeStep=System.currentTimeMillis();
            String dr=DateTimeUtil.dateTime1(new Date());
            suffix=config.getQcloudPrefix()+"/"+timeStep+suffix;
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,suffix,inputStream,metadata);
            PutObjectResult putObjectResult = client.putObject(putObjectRequest);
            client.shutdown();
            url=config.getQcloudDomain()+"/"+suffix;
        }catch (Exception e){
            return  null;
        }
        return url;
    }

    @Override
    public String downLoad(HttpServletResponse response, String url,String  path) {
        ServletOutputStream out;
        String bucketName=config.getQcloudBucketName();
        String objectName=url.replace(config.getQcloudDomain()+"/","");
        String re="";
        String localPath[]=objectName.split("\\/");
        int len=localPath.length;
        re=localPath[len-1];
        try {
            COSObject ossObject = client.getObject(bucketName, objectName);
            InputStream inputStream=ossObject.getObjectContent();
            out = response.getOutputStream();
            int L=0;
            byte[] buffers=new byte[1024];
            while((L = inputStream.read(buffers)) != -1){
                if (buffers.length!=0){
                    out.write(buffers, 0,L);
                }
            }
            if (client !=null){
                client.shutdown();
            }

            if (out != null) {
                out.flush();
                out.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return re;
    }


    public String upload(byte[] data, String path,String localPath) {
        return "";
    }

    @Override
    public String uploadFile(File file) {
        try {
// 指定文件将要存放的存储桶
            String bucketName = config.getQcloudBucketName();
// 指定文件上传到 COS 上的路径，即对象键。例如对象键为folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
            String key = UUID.randomUUID().toString();
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
            PutObjectResult putObjectResult = client.putObject(putObjectRequest);
            client.shutdown();
        }catch (Exception e){

        }
        return null;
    }
}
